{% extends base.html %} {% block head %}
<link rel="stylesheet" type="text/css" href="/static/lib/codemirror/codemirror.min.css">
<link rel="stylesheet" type="text/css" href="/static/lib/codemirror/theme/monokai.min.css">
<script type="text/javascript" src="/static/lib/codemirror/codemirror.min.js"></script>
<script type="text/javascript" src="/static/lib/codemirror/mode/markdown.js"></script>
<script type="text/javascript" src="/static/lib/codemirror/keymap/sublime.js"></script>
<script type="text/javascript" src="/static/lib/csv.js/csv.js"></script>
<script type="text/javascript" src="/static/lib/marked/marked.js"></script>
<script type="text/javascript" src="/static/lib/webuploader/webuploader.nolog.min.js"></script>
<script type="text/javascript" src="/static/js/upload.js"></script>
<script type="text/javascript" src="/static/js/marked-ext.js"></script>
<script type="text/javascript" src="/static/js/editor.js"></script>

<style>
    .CodeMirror {
        width: 100%;
        font-size: 16px;
        height: auto;
    }

    #markdown-input {
        position: relative;
        font-family: monospace;
    }

    .alert {
        color: red;
        background-color: #FFCCCC;
        width: initial;
    }

    .small {
        font-size: small;
    }

    #submit-div {
        background-color: white;
        top: 0px;
        z-index: 100
    }

    #editor-area {
        border: 1px solid #ccc;
        height: 500px;
        overflow-y: scroll;
    }

    #autosaveResult {
        color: green;
        font-size: small;
    }

    .pathlist {
        background-color: #eee;
        padding: 3px;
    }

    .toolbox {
        background-color: #eee;
        border: 1px solid #ccc;
        border-bottom: none;
    }

    .toolbox-btn {
        display: block;
        float: left;
        background-color: #eee;
        color: #000;
        border-right: 1px solid #ccc;
        outline: none;
        margin-top: 0px;
    }

    .toolbox-btn:hover {
        display: block;
        float: left;
        color: #fff;
        background-color: #aaa;
        border: 1px solid #ccc;
    }

    #markdown-output-div {
        border-left: 1px solid #ccc;
    }
</style>
{% end %} 

{% block body %} 

{% init error = "" %} 
{% init download_csv = False %}

<div class="alert">
    {{error}}
</div>

<div class="grid-card">
    <form id="mainFrame" action="/note/update" enctype="multipart/form-data" method="POST" class="col-md-12">
        <div class="col-md-12" id="submit-div">
            <div>
                <span id="fileId" class="hide">{{file.id}}</span>
            </div>
            <div class="grid-title">
                {% for i, item in enumerate(pathlist) %}
                    {% if i > 0 %} / {% end %}<a href="{{item.url}}" class="link2">{{ item.name }}</a>
                {% end %}

                <div class="float-right">
                    <button class="inline-btn">保存</button>
                </div>
            </div>
        </div>
        <div class="col-md-12">
            <span id="result" style="color:green"></span>
            <div class="col-md-12 toolbox">
                <input type="button" id="insertCode" class="toolbox-btn" value="代码" />
                <input type="button" id="insertStrong" class="toolbox-btn" value="加粗" />
                <input type="button" id="insertDel" class="toolbox-btn" value="删除线" />
                <input type="file" id="file" name="file" class="hide" />
                <input type="button" id="uploadBtn" class="toolbox-btn" value="文件" />
                <input type="button" class="toolbox-btn btn-primary" onclick="togglePreview(this)" value="预览" />
                <span id="uploadProgress" class="upload-progress"></span>
                <span id="autosaveResult" class="hide">自动保存成功</span>
            </div>

            <div class="col-md-12" id="editor-area">
                <div class="col-md-12">
                    <div id="edit-div">
                        <input style="display:none" name="id" value="{{file.id}}" />
                        <input type="text" name="version" value="{{file.version}}" class="hide" />
                        <input type="text" name="type" value="md" class="hide" />
                    </div>
                </div>

                <div class="col-md-12">
                    <div id="editor" class="col-md-12" style="height: auto; ">
                        <div id="markdown-input-div" class="col-md-12">
                            <textarea id="markdown-input" class="form-control" name="content" rows=50>{{file.content}}</textarea>
                        </div>

                        <div id="markdown-output-div" class="col-md-6 hide"></div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script type="text/javascript">
    function delLink() {
        var r = confirm("确认删除 {{file.name}}?");
        if (r) {
            location.href = "/note/update?option=del&id={{file.id}}";
        }
    }

    function codeInsert(code) {
        codeMirror.replaceSelection(code, 'around');
    }

    $("#uploadBtn").on("click", function () {
        $("#file").click();
    })

    function initMdCodeMirror() {
        if (window.codeMirror) {
            return;
        }
        var height = Math.max(500, $("#markdown-output-div").height());
        var editor = $("#markdown-input")[0];

        if ($("#markdown-input").text() == "") {
            $("#markdown-input").text("\n\n\n\n\n");
        }

        window.codeMirror = initCodeMirror("#markdown-input", {
            mode: "text/x-markdown",
            height: "auto"
        });
    }

    function edit() {
        var clientWidth = document.body.clientWidth;
        if (clientWidth < 500) {
            // 移动端CodeMirror支持不佳，经常无法触发光标
            // simpleEdit();
            // 部分功能必须依赖CodeMirror
            mobileEdit();
            return;
        } else if (clientWidth < 1000) {
            // 至少需要500px方便编写
            mobileEdit();
            return;
        }
        initMdCodeMirror();
    }

    /**
     * 使用textarea编辑，对于CodeMirror支持不好的场景下使用
     */
    function simpleEdit() {
        $("#markdown-input-div").removeClass("hide").addClass("col-md-12");
        $("#markdown-output-div").removeClass("col-md-12").addClass("hide");
        var height = Math.max(500, $("#markdown-output-div").height());
        $("#markdown-input").css({ height: height + "px" });
        $("#edit-div").show();
        $("#edit-btns").hide();
    }

    function mobileEdit() {
        $("#markdown-input-div").removeClass("hide").addClass("col-md-12");
        $("#markdown-output-div").removeClass("col-md-12").addClass("hide");
        var height = Math.max(500, $("#markdown-output-div").height());
        $("#markdown-input").css({ height: height + "px" });
        $("#edit-div").show();
        $("#edit-btns").hide();
        initMdCodeMirror();
    }

    function togglePreview(target) {
        if ($("#markdown-input-div").hasClass("col-md-12")) {
            // 全屏模式
            $("#markdown-input-div").addClass("col-md-6").removeClass("col-md-12");
            $("#markdown-output-div").removeClass("hide");
            $(target).val("关闭预览");
        } else {
            // 半屏模式
            $("#markdown-input-div").removeClass("col-md-6").addClass("col-md-12");
            $("#markdown-output-div").addClass("hide");
            $(target).val("预览");
        }
        // 重新初始化codeMirror
        codeMirror.setSize("auto", "auto");
    }

    function escape(html, encode) {
        return html
            .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/\n/g, '<br/>')
            .replace(/ /g, '&nbsp;');
    }

    $(document).ready(function () {
        var oldContent = "";
        var lastSaved = $("#markdown-input").val();
        var fileId = $("#fileId").text();
        var updatePreviewIntervalId = null;

        function updatePreview() {
            var input = $("#markdown-input").val();
            // not modified
            if (input == oldContent) {
                return;
            }
            if ($("#markdown-output-div").hasClass("hide")) {
                return;
            }
            oldContent = input;
            var outtext = marked.parse(input);
            $("#markdown-output-div").html(outtext);
        }

        function autoSave() {
            var input = $("#markdown-input").val();
            // not modified
            if (input == lastSaved) {
                return;
            }
            lastSaved = input;
            $.post("/note/save", { id: fileId, content: input }, function (resp) {
                console.log(resp);
                if (resp.code == "success") {
                    $("#autosaveResult").show().fadeOut(1000);
                }
            })
        }

        updatePreview();
        edit();

        updatePreviewIntervalId = setInterval(updatePreview, 200);
        // setInterval(autoSave, 1000*30);

        $("#insertCode").on("click", function () {
            var selection = codeMirror.getSelection();
            if (selection != "" && selection != null) {
                if (selection.indexOf('\n') >= 0) {
                    codeMirror.replaceSelection("```" + selection + "```", "around");
                } else {
                    codeMirror.replaceSelection("`" + selection + "`", "around");
                }
            } else {
                codeInsert("```\n[代码]\n```");
            }
        });

        function toggleSurround(chars) {
            var selection = codeMirror.getSelection();
            if (selection.startsWith(chars) && selection.endsWith(chars)) {
                codeMirror.replaceSelection(selection.substring(chars.length, selection.length - chars.length), "around");
            } else {
                codeMirror.replaceSelection(chars + selection + chars, "around");
            }
        }

        $("#insertStrong").on("click", function () {
            toggleSurround("**");
        });

        $("#insertDel").click(function () {
            toggleSurround("~~");
        })

        $("#formatTable").click(function () {
            // var selection = codeMirror.getSelection();
            var selection = codeMirror.doc.getValue();
            var formatedText = formatMarkdownTable(selection);
            console.log(formatedText);
            // codeMirror.replaceSelection(formatedText, "around");
            codeMirror.doc.setValue(formatedText);
        })

        // 文件上传
        var BASE_URL = "/static/lib/webuploader"
        // 初始化Web Uploader
        var uploader = xnote.createUploader();

        // 文件上传过程中创建进度条实时显示。
        uploader.on('uploadProgress', function (file, percentage) {
            var $li = $('#uploadProgress'),
                $percent = $li.find('.progress span');

            // 避免重复创建
            if (!$percent.length) {
                $percent = $('<div class="progress"><span></span></div>')
                    .appendTo($li)
                    .find('span');
            }

            $percent.css('width', percentage * 100 + '%');
            $percent.text((percentage * 100).toFixed(2) + '%');
        });

        uploader.on('uploadBeforeSend', function (object, data, headers) {
            $('#uploadProgress').find('.progress').remove();
            data.dirname = "auto";
            data.prefix = "N{{file.id}}";
            data.type = "html5";
        })

        // 文件上传成功，给item添加成功class, 用样式标记上传成功。
        uploader.on('uploadSuccess', function (file, resp) {
            $('#uploadProgress').find('.progress').remove();
            var $li = $('#uploadProgress');
            $('<div class="progress"><span>上传完成</span></div>')
                .appendTo($li)
                .find('span');
            console.log(resp);
            codeInsert(resp.link);
        });

        // 文件上传失败，显示上传出错。
        uploader.on('uploadError', function (file) {
            console.error("上传失败", file)
            var $li = $('#' + file.id),
                $error = $li.find('div.error');
            // 避免重复创建
            if (!$error.length) {
                $error = $('<div class="error"></div>').appendTo($li);
            }
            $error.text('上传失败');
        });

        $("#file").on("change", function (event) {
            console.log(event);
            var fileList = event.target.files; //获取文件对象 
            console.log(fileList);
            if (fileList && fileList.length > 0) {
                uploader.addFile(fileList);
            }
        });

        $(document).on("paste", function (e) {
            console.log(e);

            window.e = e;

            var clipboardData = e.clipboardData || e.originalEvent && e.originalEvent.clipboardData || {};

            // console.log(clipboardData);

            if (clipboardData.items) {
                arrForEach(clipboardData.items, function (item, index) {
                    var value = item.value;
                    // console.log(item, value);
                    if (/image/i.test(item.type)) {
                        console.log(item);
                        var blob = item.getAsFile();
                        xnote.uploadBlob(blob, 'N' + fileId, function (respJson) {
                            console.log(respJson);
                            var link = respJson.link;
                            codeInsert(link);
                        });
                    }
                })
            }
        });

        adjustHeight("#editor-area", 30);

        window.SUBMIT_FORM = false;

        $("#mainFrame").on("submit", function (e) {
            console.log(e);
            window.SUBMIT_FORM = true;
        });

        // 退出确认的询问
        window.onbeforeunload=function(e){
            if (window.SUBMIT_FORM) {
                console.log("form is submit");
                return;
            }
            var e = window.event||e;  
            console.log(e);
        　　e.returnValue = "确定离开当前页面吗？";
        } 
    });

</script>

<!-- GROUPS: {{file.groups}} -->
{% end %}